package pl.un4giv3n.mightvsmagic.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class AutocompleteClanAction extends PersistenceAction {
	private static final long serialVersionUID = 1L;
	private String clanName;
	private Map<String, String> json;

	public String execute() {
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	public String getClans() {
		json = new HashMap<String, String>();

		if (clanName != null && clanName.length() > 1) {
			EntityManager entityManager = getEntityManager();
			Query nativeQuery = entityManager.createNativeQuery("select name from Clan where name like :name");
			nativeQuery.setParameter("name", clanName+"%");
			List<String> clanNames = nativeQuery.getResultList();
			for (String cName : clanNames) {
				json.put(cName, cName);
			}
			entityManager.close();
		}

		return SUCCESS;
	}

	public Map<String, String> getJson() {
		return json;
	}

	public String getClanName() {
		return clanName;
	}

	public void setClanName(String clanName) {
		this.clanName = clanName;
	}

}
